blog

home / developersection / blogs / c# anonymous methods – a beginner's guide

C# Anonymous Methods – A Beginner's Guide

C# Anonymous Methods – A Beginner's Guide

Anubhav Kumar 481 22-Apr-2025

Anonymous methods in C# are a powerful feature that allows you to define inline methods without giving them a name. These methods are typically used when you need to pass behavior as a parameter to a method or delegate, but don’t want to define a full method separately.

Anonymous methods are primarily used with delegates, events, and LINQ expressions.

What is an Anonymous Method?

An anonymous method is a method without a name. Instead of defining a method separately, you write the method directly where it’s needed. Anonymous methods are often used with delegates and events.

Syntax of an Anonymous Method

You define an anonymous method with the delegate keyword. Here's the basic syntax:

delegate(parameterList) 
{
    // Method body
};

Example

Action<string> greet = delegate(string name)
{
    Console.WriteLine("Hello, " + name);
};

greet("Alice"); // Output: Hello, Alice

Example: Using Anonymous Methods with Delegates

Let’s say you have a delegate that expects a method to perform some action on an integer. Instead of defining a separate method, you can directly define the action using an anonymous method.

using System;

class Program
{
    delegate void ProcessNumber(int number);

    static void Main()
    {
        ProcessNumber process = delegate(int number)
        {
            Console.WriteLine("Processing number: " + number);
        };

        process(5);  // Output: Processing number: 5
    }
}

In this example:

  1. ProcessNumber is a delegate type.
  2. The anonymous method receives an integer and processes it.

Anonymous Methods with Multiple Parameters

Anonymous methods can have multiple parameters, just like regular methods.

using System;

class Program
{
    delegate int AddNumber(int x, int y);

    static void Main()
    {
        AddNumber add = delegate(int x, int y)
        {
            return x + y;
        };

        int result = add(5, 3);
        Console.WriteLine(result);  // Output: 8
    }
}

Anonymous Methods with Events

Anonymous methods are also frequently used to handle events without needing to define a separate event handler method.

using System;

class Button
{
    public event Action OnClick;

    public void Click()
    {
        OnClick?.Invoke();  // Trigger the event
    }
}

class Program
{
    static void Main()
    {
        Button button = new Button();

        // Attach an anonymous method to the event
        button.OnClick += delegate
        {
            Console.WriteLine("Button clicked!");
        };

        button.Click();  // Output: Button clicked!
    }
}

Advantages of Anonymous Methods

  1. Concise: No need to create a separate method.
  2. Local Scope: Anonymous methods can be written where they are needed, making them easy to understand and maintain.
  3. Flexibility: Especially useful when you don’t need to reuse the method elsewhere.

Anonymous Methods vs Lambda Expressions

Lambda expressions, introduced in C# 3.0, are a more concise and flexible way of writing anonymous methods.

Lambda Expression Example:

Action<string> greet = name => Console.WriteLine("Hello, " + name);
greet("Alice");  // Output: Hello, Alice

Key Differences:

  1. Lambda expressions are more compact than anonymous methods.
  2. Anonymous methods use the delegate keyword, while lambda expressions use =>.

Summary

Concept Description
What is it? A method without a name
Syntax delegate keyword
Use Case Inline methods for delegates and events
Flexibility Often used in delegates, LINQ, and events
Difference with Lambdas Lambdas are more concise and commonly used

Anonymous methods are a great way to write compact, inline code for simple tasks. They're especially useful in event handling and delegating tasks dynamically. However, with the introduction of lambda expressions, many developers prefer lambdas for their clarity and brevity.


c# c# 
Updated 22-Apr-2025
Anubhav Kumar

Student

The Anubhav portal was launched in March 2015 at the behest of the Hon'ble Prime Minister for retiring government officials to leave a record of their experiences while in Govt service .

Leave Comment

Comments

Liked By